package com.ytjj.qmyx.supplychain.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.kuaidi100.sdk.enums.ExpressEnums;
import com.kuaidi100.sdk.response.QueryTrackData;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.enums.ExceptionOrderClassifyEnum;
import com.ytjj.qmyx.supplychain.common.enums.ReissueTypeEnums;
import com.ytjj.qmyx.supplychain.common.exception.ApiException;
import com.ytjj.qmyx.supplychain.common.model.OrderExceptionNoteVO;
import com.ytjj.qmyx.supplychain.common.model.excel.OrdersExceptionExcel;
import com.ytjj.qmyx.supplychain.common.model.request.BankerRequest;
import com.ytjj.qmyx.supplychain.common.model.request.ExceptionOrdersRequest;
import com.ytjj.qmyx.supplychain.common.model.response.*;
import com.ytjj.qmyx.supplychain.common.utils.DateUtil;
import com.ytjj.qmyx.supplychain.common.utils.TokenUtil;
import com.ytjj.qmyx.supplychain.mapper.*;
import com.ytjj.qmyx.supplychain.mapper.entity.*;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderExceptionService {
    @Resource
    private OrderExceptionMapper orderExceptionMapper;
    @Resource
    private OrderExceptionNoteMapper orderExceptionNoteMapper;
    @Resource
    private BankerOrderMapper bankerOrderMapper;
    @Autowired
    private ShopInfoService shopInfoService;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private BankerMapper bankerMapper;
    @Resource
    private BankerService bankerService;
    @Resource
    private ExpressOrdersMapper expressOrdersMapper;
    @Resource
    private ReissueLogisticsMapper reissueLogisticsMapper;

    /**
     * 获取异常订单
     *
     * @param exceptionOrdersRequest
     * @return CommonPage
     */
    public CommonPage getExceptionOrders(ExceptionOrdersRequest exceptionOrdersRequest) {
        if (exceptionOrdersRequest.getRequestType() == 0) {
            String partentId = TokenUtil.getPartentId();
            log.info("===partentId==={}", partentId);
            if (!StringUtils.isEmpty(partentId)) {
                YxShopInfo shopInfo = shopInfoService.queryShopInfoByPartnerId(partentId);
                exceptionOrdersRequest.setShopId(Arrays.asList(shopInfo.getShopId()));
            }
        }
        if (!StringUtil.isBlank(exceptionOrdersRequest.getBuyer())) {
            BankerRequest bankerRequest = new BankerRequest();
            bankerRequest.setBuyer(exceptionOrdersRequest.getBuyer());
            List<Integer> ids = bankerMapper.selectByRequest(bankerRequest);
            exceptionOrdersRequest.setBankerIds(ids);
        }
        if (exceptionOrdersRequest.getBankerId() != null) {
            List<Integer> bankerIds = Optional.ofNullable(exceptionOrdersRequest.getBankerIds()).orElse(new ArrayList<>());
            bankerIds.add(exceptionOrdersRequest.getBankerId());
            exceptionOrdersRequest.setBankerIds(bankerIds);
        }

        log.info("===exceptionOrdersRequest==={}", JSONObject.toJSONString(exceptionOrdersRequest));
        if (exceptionOrdersRequest.getPageHelper() == null || exceptionOrdersRequest.getPageHelper() == 0) {
            PageHelper.startPage(exceptionOrdersRequest.getPageNum(), exceptionOrdersRequest.getPageSize());
        }
        List<YxOrderException> yxOrderExceptionList = Optional.ofNullable(orderExceptionMapper.getAllExceptionOrders(exceptionOrdersRequest))
                .orElse(new ArrayList<>());

        CommonPage commonPage = CommonPage.restPage(yxOrderExceptionList);

        if (CollectionUtils.isEmpty(yxOrderExceptionList)) {
            return commonPage;
        }
        //供应商信息
        List<Integer> bankerIds = yxOrderExceptionList.stream().map(YxOrderException::getBankerId).collect(Collectors.toList());
        List<BankerResponse> bankerResponses = productMapper.selectBankerMsgByBankerId(bankerIds);
        Map<Integer, List<BankerResponse>> bankers = bankerResponses.stream().collect(Collectors.groupingBy(BankerResponse::getBankerId));
        //补货单号
        Set<String> childOrderNos = yxOrderExceptionList.stream().map(YxOrderException::getChildOrderNo).collect(Collectors.toSet());
        List<YxReissueLogistics> latestByChildOrderNos = reissueLogisticsMapper.getLatestByChildOrderNo(new ArrayList<>(childOrderNos));
        Map<String,List<YxReissueLogistics>> reissueMap = latestByChildOrderNos.stream().collect(Collectors.groupingBy(YxReissueLogistics::getChildOrderNo));
        //最新备注
        List<Integer> ids = yxOrderExceptionList.stream().map(YxOrderException::getId).collect(Collectors.toList());
        List<YxOrderExceptionNote> orderExceptionNote = orderExceptionNoteMapper.getOrderExceptionNote(ids);
        Map<Integer, List<YxOrderExceptionNote>> noteMap = orderExceptionNote.stream().collect(Collectors.groupingBy(YxOrderExceptionNote::getOrderExceptionId));
        commonPage.setList(yxOrderExceptionList.stream()
                .map(item -> {
                    //数据脱敏
                    if (exceptionOrdersRequest.getRequestType() == 0 && !StringUtils.isEmpty(item.getUserTel())) {
                        String userTel = item.getUserTel().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
                        item.setUserTel(userTel);
                    }
                    OrdersExceptionResponse ordersExceptionResponse = new OrdersExceptionResponse();
                    BeanUtils.copyProperties(item, ordersExceptionResponse);
                    ordersExceptionResponse.setTypeno(this.getTypeno(item.getChildOrderNo()));
                    List<YxOrderExceptionNote> orderExceptionNotes = noteMap.get(item.getId());
                    List<OrderExceptionNoteVO> voList = new ArrayList<>();
                    if(!CollectionUtils.isEmpty(orderExceptionNotes)){
                        orderExceptionNotes.stream().forEach(note -> {
                            OrderExceptionNoteVO vo = new OrderExceptionNoteVO();
                            BeanUtils.copyProperties(note, vo);
                            voList.add(vo);
                        });
                    }
                    ordersExceptionResponse.setExceptionOrderNoteList(voList);
                    if (null != item.getExceptionClassify()) {
                        Integer type = Integer.valueOf(item.getExceptionClassify());
                        String classifyName = ExceptionOrderClassifyEnum.getClassifyNameByType(type);
                        if (!StringUtils.isEmpty(classifyName)) {
                            ordersExceptionResponse.setExceptionClassify(classifyName);
                        }
                    }

                    String substring = ordersExceptionResponse.getChildOrderNo().substring(0, 1);
                    if (substring.equals("MZ")) {
                        ordersExceptionResponse.setOrderSource("yxyx");
                    }else if (substring.equals("D")) {
                        ordersExceptionResponse.setOrderSource("聚卖多");
                    } else if (substring.equals("F")) {
                        ordersExceptionResponse.setOrderSource("xxxx商城");
                    }
                    //采购员
                    List<BankerResponse> nowBanker = bankers.get(item.getBankerId());
                    if (!CollectionUtils.isEmpty(nowBanker)) {
                        ordersExceptionResponse.setBuyer(nowBanker.get(0).getBuyer());
                    }

                    List<String> replenishmentInfo = new ArrayList<>();
                    List<YxReissueLogistics> nowReissueLogistics = reissueMap.get(item.getChildOrderNo());
                    if(!CollectionUtils.isEmpty(nowReissueLogistics)){
                        for (YxReissueLogistics yxReissueLogistics : nowReissueLogistics) {
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String format = "";
                            if(yxReissueLogistics.getSupplementaryDay() != null){
                                format = simpleDateFormat.format(yxReissueLogistics.getSupplementaryDay());
                            }
                            String message = Optional.ofNullable(ReissueTypeEnums.getMessageByCode(yxReissueLogistics.getReissueType())).orElse("");
                            replenishmentInfo.add(message + format + " " + yxReissueLogistics.getExpressCompanyName() + " " + yxReissueLogistics.getExpressNo());
                        }
                    }
                    ordersExceptionResponse.setReplenishmentInfo(String.join("||", replenishmentInfo));
                    return ordersExceptionResponse;
                })
                .collect(Collectors.toList()));
        return commonPage;
    }

    /**
     * 异常订单统计
     *
     * @param exceptionOrdersRequest
     * @return CommonPage
     */
    public List<ExceptionStatisticsResponse> getExceptionOrdersStatistics(ExceptionOrdersRequest exceptionOrdersRequest) {
        if (exceptionOrdersRequest.getRequestType() == 0) {
            String partentId = TokenUtil.getPartentId();
            log.info("===partentId==={}", partentId);
            if (!StringUtils.isEmpty(partentId)) {
                YxShopInfo shopInfo = shopInfoService.queryShopInfoByPartnerId(partentId);
                exceptionOrdersRequest.setShopId(Arrays.asList(shopInfo.getShopId()));
            }
        }
        if (!StringUtil.isBlank(exceptionOrdersRequest.getBuyer())) {
            BankerRequest bankerRequest = new BankerRequest();
            bankerRequest.setBuyer(exceptionOrdersRequest.getBuyer());
            List<Integer> ids = bankerMapper.selectByRequest(bankerRequest);
            exceptionOrdersRequest.setBankerIds(ids);
        }
        if (exceptionOrdersRequest.getBankerId() != null) {
            List<Integer> bankerIds = Optional.ofNullable(exceptionOrdersRequest.getBankerIds()).orElse(new ArrayList<>());
            bankerIds.add(exceptionOrdersRequest.getBankerId());
            exceptionOrdersRequest.setBankerIds(bankerIds);
        }

        List<ExceptionStatisticsResponse> exceptionData = orderExceptionMapper.getExceptionOrdersStatistics(exceptionOrdersRequest);
        Map<String, String> map = exceptionData.stream().collect(Collectors.toMap(e -> e.getKey(), ExceptionStatisticsResponse::getTotal));
        Map<String, String> allExpressException = ExpressEnums.getAllExpressException();
        List<ExceptionStatisticsResponse> responses = new ArrayList<>();
        for (Map.Entry<String, String> entry : allExpressException.entrySet()) {
            ExceptionStatisticsResponse statisticsResponse = new ExceptionStatisticsResponse();
            statisticsResponse.setKey(entry.getKey());
            statisticsResponse.setName(entry.getValue());
            Object total = map.get(entry.getKey());
            if (total != null) {
                statisticsResponse.setTotal(total.toString());
            } else {
                statisticsResponse.setTotal("0");
            }
            responses.add(statisticsResponse);
        }
        return responses;
    }


    public String getTypeno(String orderNo) {
        String typeno = bankerOrderMapper.getTypenoNewByChildOrderNo(orderNo);
        return typeno;
    }

    /**
     * 获取符合条件的所有的异常订单
     */
    public List<OrdersExceptionResponse> getAllExceptionOrders(ExceptionOrdersRequest exceptionOrdersRequest) {
        if (exceptionOrdersRequest.getBankerId() != null) {
            List<Integer> bankerIds = Optional.ofNullable(exceptionOrdersRequest.getBankerIds()).orElse(new ArrayList<>());
            bankerIds.add(exceptionOrdersRequest.getBankerId());
            exceptionOrdersRequest.setBankerIds(bankerIds);
        }
        List<YxOrderException> exceptionOrderList = orderExceptionMapper.getAllExceptionOrders(exceptionOrdersRequest);
        if (CollectionUtils.isEmpty(exceptionOrderList)) {
            return new ArrayList<>();
        }
        //供应商id集合
        Set<Integer> bankerIds = new HashSet<>();
        //子订单号集合
        Set<String> childOrderNos = new HashSet<>();
        //异常订单id集合
        List<Integer> ids = new ArrayList<>();
        exceptionOrderList.stream().forEach(e->{
            ids.add(e.getId());
            bankerIds.add(e.getBankerId());
            childOrderNos.add(e.getChildOrderNo());
        });
        //供应商
        List<BankerResponse> bankerResponses = productMapper.selectBankerMsgByBankerId(new ArrayList<>(bankerIds));
        Map<Integer, List<BankerResponse>> bankerMap = bankerResponses.stream().collect(Collectors.groupingBy(BankerResponse::getBankerId));
        //异常订单备注
        List<YxOrderExceptionNote> orderExceptionNotes = orderExceptionNoteMapper.getOrderExceptionNote(ids);
        Map<Integer, List<YxOrderExceptionNote>> exceptionNotes = orderExceptionNotes.stream().collect(Collectors.groupingBy(YxOrderExceptionNote::getOrderExceptionId));
        //补货单号
        List<YxReissueLogistics> latestByChildOrderNos = reissueLogisticsMapper.getLatestByChildOrderNo(new ArrayList<>(childOrderNos));
        Map<String,List<YxReissueLogistics>> reissueMap = latestByChildOrderNos.stream().collect(Collectors.groupingBy(YxReissueLogistics::getChildOrderNo));
        return exceptionOrderList.stream()
                .map(item -> {
                    OrdersExceptionResponse ordersExceptionResponse = new OrdersExceptionResponse();
                    BeanUtils.copyProperties(item, ordersExceptionResponse);
                    //采购员
                    List<BankerResponse> bankers = bankerMap.get(item.getBankerId());
                    if(!CollectionUtils.isEmpty(bankers)){
                        ordersExceptionResponse.setBuyer(bankers.get(0).getBuyer());
                        //来源是供应链，则显示供应商名称
                        if (exceptionOrdersRequest.getRequestType() != null && exceptionOrdersRequest.getRequestType() == 1) {
                            ordersExceptionResponse.setBankerName(bankers.get(0).getBankerName());
                        } else {
                            ordersExceptionResponse.setBankerName("");
                        }
                    }
                    if (null != item.getExceptionClassify()) {
                        Integer type = Integer.valueOf(item.getExceptionClassify());
                        String classifyName = ExceptionOrderClassifyEnum.getClassifyNameByType(type);
                        if (!StringUtils.isEmpty(classifyName)) {
                            ordersExceptionResponse.setExceptionClassify(classifyName);
                        }
                    }
                    //处理快递流水，取新的一条
                    String expressRecord = item.getExpressRecord();
                    try {
                        List<QueryTrackData> data = JSONArray.parseArray(expressRecord, QueryTrackData.class);
                        if (!CollectionUtils.isEmpty(data)){
                            QueryTrackData queryTrackData = data.get(0);
                            expressRecord = queryTrackData.getFtime()+" "+queryTrackData.getContext();
                        }
                    } catch (Exception ex) {
                        expressRecord = item.getExpressRecord();
                    }
                    ordersExceptionResponse.setExpressRecord(expressRecord);
                    //处理历史备注
                    List<YxOrderExceptionNote> nowNotes = exceptionNotes.get(item.getId());
                    if(!CollectionUtils.isEmpty(nowNotes)){
                        List<String> handleText = nowNotes.stream().limit(5).map(e ->
                                DateUtil.dateToStr(e.getCreateTime()) + " " + e.getAdminName() + ":" + e.getContent()
                        ).collect(Collectors.toList());
                        ordersExceptionResponse.setHandleResult(String.join("||",handleText));
                    }
                    //补货单号
                    List<String> replenishmentInfo = new ArrayList<>();
                    List<YxReissueLogistics> nowReissueLogistics = reissueMap.get(item.getChildOrderNo());
                    if(!CollectionUtils.isEmpty(nowReissueLogistics)){
                        for (YxReissueLogistics yxReissueLogistics : nowReissueLogistics) {
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String format = "";
                            if(yxReissueLogistics.getSupplementaryDay() != null){
                                format = simpleDateFormat.format(yxReissueLogistics.getSupplementaryDay());
                            }
                            String message = Optional.ofNullable(ReissueTypeEnums.getMessageByCode(yxReissueLogistics.getReissueType())).orElse("");
                            replenishmentInfo.add(message + format + " " + yxReissueLogistics.getExpressCompanyName() + " " + yxReissueLogistics.getExpressNo());
                        }
                    }
                    ordersExceptionResponse.setReplenishmentInfo(String.join("||", replenishmentInfo));
                    return ordersExceptionResponse;
                })
                .collect(Collectors.toList());
    }


    /**
     * 更新异常订单
     */
    @Transactional(rollbackFor = Exception.class)
    public List<ImportExcelFailResponse> updateExceptionHandle(List<ExceptionOrdersRequest> requests) {
        if(requests.size() == 0){
            throw new ApiException("数据为空！");
        }
        List<ImportExcelFailResponse> responses = new ArrayList<>();
        for (ExceptionOrdersRequest request : requests) {
            ImportExcelFailResponse response = new ImportExcelFailResponse();
            Date createTime =  new Date();
            //记录备注
            if (!StringUtils.isEmpty(request.getExceptionOrderNote())) {
                YxOrderExceptionNote note = new YxOrderExceptionNote();
                note.setOrderExceptionId(request.getId());
                note.setAdminName(request.getHandlePerson());
                note.setContent("【备注】" + request.getExceptionOrderNote());
                note.setCreateTime(createTime);
                orderExceptionNoteMapper.insert(note);
            }
            YxOrderException nowOrderException = orderExceptionMapper.selectByPrimaryKey(request.getId());
            if (nowOrderException ==null){
                continue;
            }
            YxOrderException yxOrderException = new YxOrderException();
            yxOrderException.setId(request.getId());
            boolean finishedMark = false;
            boolean isHandle = false;
            //设置异常单为处理状态,并记录处理备注
            if (request.getStatus() != null && "2".equals(request.getStatus().toString()) && nowOrderException.getStatus().equals((byte) 1)) {
                if (StringUtils.isEmpty(request.getHandleNote())) {
                    response.setId(request.getId());
                    response.setMsg("处理备注不能为空！");
                    responses.add(response);
                    continue;
                }
                YxOrderExceptionNote note = new YxOrderExceptionNote();
                note.setOrderExceptionId(request.getId());
                note.setAdminName(request.getHandlePerson());
                note.setContent("【已处理】" + request.getHandleNote());
                note.setCreateTime(createTime);
                orderExceptionNoteMapper.insert(note);
                yxOrderException.setStatus((byte) 2);
                yxOrderException.setHandleTime(createTime);
                yxOrderException.setHandlePerson(request.getHandlePerson());
                isHandle = true;
            }
            //设置异常订单已完结,并记录完结备注
            if (request.getIsFinished() != null && request.getIsFinished() == 1 && nowOrderException.getIsFinished() != 1) {
                if (StringUtils.isEmpty(request.getFinishedRemarks())) {
                    response.setId(request.getId());
                    response.setMsg("完结备注不能为空！");
                    responses.add(response);
                    continue;
                }
                YxOrderExceptionNote note = new YxOrderExceptionNote();
                note.setOrderExceptionId(request.getId());
                note.setAdminName(request.getHandlePerson());
                note.setContent("【已标记完结】" + request.getFinishedRemarks());
                note.setCreateTime(createTime);
                orderExceptionNoteMapper.insert(note);
                yxOrderException.setIsFinished(request.getIsFinished());
                finishedMark = true;
            }
            if(isHandle || finishedMark || request.getExceptionClassify() != null){
                orderExceptionMapper.updateByPrimaryKeySelective(yxOrderException);
            }
        }
        return responses;
    }

    /**
     * 批量备注
     * @param ids
     * @param content
     * @param adminName
     * @return void
     */
    public CommonResult insertNoteBatch(String ids, String content, String adminName){
        if(StringUtils.isEmpty(ids)){
            return CommonResult.failed("至少选择一项！");
        }
        String[] split = ids.split(",");
        Date createTime = new Date();
        for (String id : split) {
            YxOrderExceptionNote yxOrderExceptionNote = new YxOrderExceptionNote();
            yxOrderExceptionNote.setCreateTime(createTime);
            yxOrderExceptionNote.setContent("【备注】" + content);
            yxOrderExceptionNote.setOrderExceptionId(Integer.parseInt(id));
            yxOrderExceptionNote.setAdminName(adminName);
            orderExceptionNoteMapper.insertSelective(yxOrderExceptionNote);
        }
        return CommonResult.success();
    }


    public List<YxOrderExceptionNote> selectNote(Integer id) {
        Example example = new Example(YxOrderExceptionNote.class);
        example.createCriteria().andEqualTo("orderExceptionId", id);
        example.orderBy("id").desc();
        List<YxOrderExceptionNote> list = orderExceptionNoteMapper.selectByExample(example);
        return list;
    }

    public YxOrderException findOrderExceptionByChildOrderNo(String childOrderNo) {
        return orderExceptionMapper.findOrderExceptionByChildOrderNo(childOrderNo);
    }

    public YxOrderException selectByExpressCodeAndExpressNo(String expressCode, String expressNo) {
        Example example = new Example(YxOrderException.class);
        example.createCriteria().andEqualTo("expressCode", expressCode).andEqualTo("expressNo", expressNo);
        example.orderBy("id").desc();
        List<YxOrderException> orderExceptionList = orderExceptionMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(orderExceptionList)) {
            return null;
        }
        return orderExceptionList.get(0);
    }

    /**
     * 获取所有异常值列表
     */
    public Map<String, String> getAllExpressException() {
        Map<String, String> allExpressException = ExpressEnums.getAllExpressException();
        return allExpressException;
    }

    /**
     * 导出异常订单
     */
    public void exportExceptionOrders(HttpServletResponse response,ExceptionOrdersRequest request){
        log.info("====getExceptionOrders==={}", request);
        Pattern pattern = Pattern.compile("-?[0-9]+(\\\\.[0-9]+)?");
        YxBanker userInfo = bankerService.getUserInfo();
        request.setBankerId(userInfo.getId());
        request.setRequestType(1);
        request.setPageHelper(1);
        CommonPage<OrdersExceptionResponse> commonPage = getExceptionOrders(request);
        List<OrdersExceptionResponse> OrdersExceptionResponseList = commonPage.getList();
        List<OrdersExceptionExcel> ordersExceptionExcels = new ArrayList<>();
        OrdersExceptionResponseList.stream().forEach(e->{
            OrdersExceptionExcel ordersExceptionExcel = new OrdersExceptionExcel();
            BeanUtils.copyProperties(e,ordersExceptionExcel);
            if("2".equals(e.getStatus().toString())){
                ordersExceptionExcel.setStatusText("已处理");
            }else if("1".equals(e.getStatus().toString())){
                ordersExceptionExcel.setStatusText("未处理");
            }
            //处理快递流水，取新的一条
            String expressRecord = e.getExpressRecord();
            try {
                List<QueryTrackData> data = JSONArray.parseArray(expressRecord, QueryTrackData.class);
                if (!CollectionUtils.isEmpty(data)){
                    QueryTrackData queryTrackData = data.get(0);
                    expressRecord = queryTrackData.getFtime()+" "+queryTrackData.getContext();
                }
            } catch (Exception ex) {
                expressRecord = e.getExpressRecord();
            }
            //脱敏处理人
            String handlePerson = ordersExceptionExcel.getHandlePerson();
            //脱敏备注人
            if (!StringUtils.isEmpty(handlePerson)) {
                Matcher m = pattern.matcher(handlePerson);
                //非id值
                if (!m.matches()) {
                    StringBuffer sb = new StringBuffer(handlePerson);
                    if (sb.length() > 1) {
                        sb.replace(1, 2, "*");
                    }
                    ordersExceptionExcel.setHandlePerson(sb.toString());
                }
            }
            //处理历史备注
            List<OrderExceptionNoteVO> exceptionOrderNoteList = e.getExceptionOrderNoteList();
            List<String> handleText = exceptionOrderNoteList.stream().map(item ->{
                        String adminName = item.getAdminName();
                        //脱敏备注人
                        if (!StringUtils.isEmpty(adminName)) {
                            Matcher m = pattern.matcher(adminName);
                            //非id值
                            if (!m.matches()) {
                                StringBuffer sb = new StringBuffer(adminName);
                                if (sb.length() > 1) {
                                    sb.replace(1, 2, "*");
                                }
                                item.setAdminName(sb.toString());
                            }
                        }
                        return DateUtil.dateToStr(item.getCreateTime()) + " " + item.getAdminName() + ":" + item.getContent();
                    }
            ).collect(Collectors.toList());
            ordersExceptionExcel.setHandleResult(String.join("||",handleText));
            ordersExceptionExcel.setExpressRecord(expressRecord);
            ordersExceptionExcels.add(ordersExceptionExcel);
        });
        try {
            String fileName = "异常订单.xls";
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            // 设置背景颜色
            headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
            // 设置头字体
            WriteFont headWriteFont = new WriteFont();
            headWriteFont.setFontHeightInPoints((short) 14);
            // 字体加粗
            headWriteFont.setBold(true);
            headWriteCellStyle.setWriteFont(headWriteFont);
            // 设置头居中
            headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

            // 内容策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            // 设置内容字体
            WriteFont contentWriteFont = new WriteFont();
            contentWriteFont.setFontHeightInPoints((short) 12);
            contentWriteFont.setFontName("宋体");
            contentWriteCellStyle.setWriteFont(contentWriteFont);
            // 设置 水平居中
//            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            // 设置 垂直居中
//            contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            // 设置单元格格式为 文本
            contentWriteCellStyle.setDataFormat((short) 49);

            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            // 设置表名，引脚名，文件格式，list数据
            EasyExcel.write(response.getOutputStream(), OrdersExceptionExcel.class)
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .sheet("异常订单")
                    .doWrite(ordersExceptionExcels);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public CommonResult batchDealExceptionOrders(Integer[] ids,Integer type){
        if(null == type){
            throw new ApiException("请选择异常分类！");
        }
        String classifyName = ExceptionOrderClassifyEnum.getClassifyNameByType(type);
        if(org.springframework.util.StringUtils.isEmpty(classifyName)){
            throw new ApiException("您选择的异常分类不存在！");
        }
        for (Integer id : ids) {
            YxOrderException yxOrderException = new YxOrderException();
            yxOrderException.setId(id);
            yxOrderException.setExceptionClassify(type);
            yxOrderException.setUpdateTime(new Date());
            orderExceptionMapper.updateByPrimaryKeySelective(yxOrderException);
        }
        return CommonResult.success();
    }

    public List<OrderExceptionNoteResponse> selectNoteByChildrenOrderNo(List<String> childrenOrderNoList) {
        List<YxOrderException> orderExceptions = orderExceptionMapper.findOrderExceptions(childrenOrderNoList);
        List<OrderExceptionNoteResponse> notes = new ArrayList<>();
        if (!CollectionUtils.isEmpty(orderExceptions)) {
            for (YxOrderException orderException : orderExceptions) {
                List<OrderExceptionNoteResponse> yxOrderExceptionNotes = orderExceptionNoteMapper.queryByOrderExceptionId(orderException.getId());
                notes.addAll(yxOrderExceptionNotes);
            }
            return notes;
        }
        return null;
    }
}
